package com.example.demo.beans;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectionExample {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {

        Class<?> clazz = MyClass.class;

// 获取类上的注解
        MyAnnotation classAnnotation = clazz.getAnnotation(MyAnnotation.class);
        System.out.println(classAnnotation.value()); // 输出 "Class Annotation"

// 获取字段上的注解
        Field field = clazz.getField("myField");
        MyAnnotation fieldAnnotation = field.getAnnotation(MyAnnotation.class);
        System.out.println(fieldAnnotation.value()); // 输出 "Field Annotation"

// 获取方法上的注解
        Method method = clazz.getMethod("myMethod");
        MyAnnotation methodAnnotation = method.getAnnotation(MyAnnotation.class);
        System.out.println(methodAnnotation.value()); // 输出 "Method Annotation"
    }
}

@MyAnnotation("Class Annotation")
class MyClass {
    @MyAnnotation("Field Annotation")
    public int myField;

    @MyAnnotation("Method Annotation")
    public void myMethod() {}
}

@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
    String value();
}
